from django.db import models
from django.utils import timezone
from users.models import User
import json


class TestReport(models.Model):
    """测试报告模型"""
    REPORT_TYPES = (
        ('ui_suite', 'UI测试套件'),
        ('api_suite', 'API测试套件'),
        ('ui_case', 'UI测试用例'),
        ('api_case', 'API测试用例'),
        ('task', '定时任务'),
    )
    STATUS_CHOICES = (
        ('passed', '通过'),
        ('failed', '失败'),
        ('partial', '部分通过'),
        ('error', '错误'),
    )

    name = models.CharField(max_length=200, verbose_name="报告名称")
    report_type = models.CharField(max_length=20, choices=REPORT_TYPES, verbose_name="报告类型")
    target_id = models.IntegerField(verbose_name="目标ID")  # 套件ID、用例ID或任务ID
    target_name = models.CharField(max_length=200, verbose_name="目标名称")

    # 执行统计
    total_cases = models.IntegerField(default=0, verbose_name="总用例数")
    passed_cases = models.IntegerField(default=0, verbose_name="通过用例数")
    failed_cases = models.IntegerField(default=0, verbose_name="失败用例数")
    skipped_cases = models.IntegerField(default=0, verbose_name="跳过用例数")
    error_cases = models.IntegerField(default=0, verbose_name="错误用例数")

    # 时间信息
    start_time = models.DateTimeField(verbose_name="开始时间")
    end_time = models.DateTimeField(verbose_name="结束时间")
    duration = models.FloatField(default=0.0, verbose_name="执行时长(秒)")

    # 状态和结果
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, verbose_name="执行状态")
    pass_rate = models.FloatField(default=0.0, verbose_name="通过率")

    # 详细数据
    execution_data = models.TextField(default='{}', verbose_name="执行数据")
    summary = models.TextField(blank=True, verbose_name="报告摘要")

    # 附件信息
    has_attachment = models.BooleanField(default=False, verbose_name="是否有附件")
    attachment_path = models.CharField(max_length=500, blank=True, verbose_name="附件路径")

    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="创建人")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    def __str__(self):
        return f"{self.name} - {self.created_at}"

    def save(self, *args, **kwargs):
        # 自动计算通过率
        if self.total_cases > 0:
            self.pass_rate = (self.passed_cases / self.total_cases) * 100
        else:
            self.pass_rate = 0.0

        # 自动确定状态
        if self.failed_cases == 0 and self.error_cases == 0:
            self.status = 'passed'
        elif self.passed_cases == 0:
            self.status = 'failed'
        else:
            self.status = 'partial'

        super().save(*args, **kwargs)

    class Meta:
        verbose_name = "测试报告"
        verbose_name_plural = "测试报告"
        ordering = ['-created_at']


class ReportDetail(models.Model):
    """报告详情模型"""
    report = models.ForeignKey(TestReport, on_delete=models.CASCADE, related_name='details', verbose_name="测试报告")
    case_name = models.CharField(max_length=200, verbose_name="用例名称")
    case_type = models.CharField(max_length=50, verbose_name="用例类型")
    status = models.CharField(max_length=20, choices=(
        ('passed', '通过'),
        ('failed', '失败'),
        ('skipped', '跳过'),
        ('error', '错误'),
    ), verbose_name="执行状态")
    duration = models.FloatField(default=0.0, verbose_name="执行时长(秒)")
    start_time = models.DateTimeField(verbose_name="开始时间")
    end_time = models.DateTimeField(verbose_name="结束时间")
    log = models.TextField(blank=True, verbose_name="执行日志")
    error_message = models.TextField(blank=True, verbose_name="错误信息")
    screenshot_path = models.CharField(max_length=500, blank=True, verbose_name="截图路径")

    def __str__(self):
        return f"{self.case_name} - {self.status}"

    class Meta:
        verbose_name = "报告详情"
        verbose_name_plural = "报告详情"
        ordering = ['start_time']


class Dashboard(models.Model):
    """仪表盘数据模型"""
    date = models.DateField(unique=True, verbose_name="统计日期")

    # UI测试统计
    ui_total_cases = models.IntegerField(default=0, verbose_name="UI总用例数")
    ui_executed_cases = models.IntegerField(default=0, verbose_name="UI已执行用例数")
    ui_passed_cases = models.IntegerField(default=0, verbose_name="UI通过用例数")
    ui_failed_cases = models.IntegerField(default=0, verbose_name="UI失败用例数")
    ui_pass_rate = models.FloatField(default=0.0, verbose_name="UI通过率")

    # API测试统计
    api_total_cases = models.IntegerField(default=0, verbose_name="API总用例数")
    api_executed_cases = models.IntegerField(default=0, verbose_name="API已执行用例数")
    api_passed_cases = models.IntegerField(default=0, verbose_name="API通过用例数")
    api_failed_cases = models.IntegerField(default=0, verbose_name="API失败用例数")
    api_pass_rate = models.FloatField(default=0.0, verbose_name="API通过率")

    # 任务统计
    total_tasks = models.IntegerField(default=0, verbose_name="总任务数")
    executed_tasks = models.IntegerField(default=0, verbose_name="已执行任务数")
    successful_tasks = models.IntegerField(default=0, verbose_name="成功任务数")
    failed_tasks = models.IntegerField(default=0, verbose_name="失败任务数")

    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    def __str__(self):
        return f"仪表盘数据 - {self.date}"

    class Meta:
        verbose_name = "仪表盘数据"
        verbose_name_plural = "仪表盘数据"
        ordering = ['-date']